package org.jeecg.modules.flower.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.vo.FlowerOutorderPrePage;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 预出库单主表
 * @Author: jeecg-boot
 * @Date: 2022-06-27
 * @Version: V1.0
 */
@Api(tags = "预出库单主表")
@RestController
@RequestMapping("/flower/flowerOutorderPre")
@Slf4j
public class FlowerOutorderPreController {
    @Autowired
    private IFlowerOutorderPreService flowerOutorderPreService;
    @Autowired
    private IFlowerOutorderPreinfoService flowerOutorderPreinfoService;

    @Autowired
    private IFlowerTagpreService flowerTagpreService;
    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;
    @Value("${yth.tempPreExcelOut}")
    private String tempPreExcelOut;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;
    @Autowired
    private IFlowerSettleAccountsService settleAccountsService;

    @Autowired
    @Lazy
    private RedisUtil redisUtil;
    /**
     * 分页列表查询
     *
     * @param flowerOutorderPre
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "预出库单主表-分页列表查询")
    @ApiOperation(value = "预出库单主表-分页列表查询", notes = "预出库单主表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/FlowerOutorderPreList")
    public Result<?> queryPageList(FlowerOutorderPre flowerOutorderPre,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                   @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
//        QueryWrapper<FlowerOutorderPre> queryWrapper = QueryGenerator.initQueryWrapper(flowerOutorderPre, req.getParameterMap());
        QueryWrapper<FlowerOutorderPre> queryWrapper = new QueryWrapper<>();
                Page<FlowerOutorderPre> page = new Page<FlowerOutorderPre>(pageNo, pageSize);
        if (StringUtils.isNotBlank(flowerOutorderPre.getOrderNo())) {
            queryWrapper.like("order_no", flowerOutorderPre.getOrderNo());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getCreateBy())) {
            queryWrapper.eq("create_user", flowerOutorderPre.getCreateBy());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getStockOutUser())) {
            queryWrapper.eq("stock_out_user", flowerOutorderPre.getStockOutUser());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getChannel())) {
            queryWrapper.eq("channel", flowerOutorderPre.getChannel());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if ( flowerOutorderPre.getState() !=null) {
            queryWrapper.eq("state", flowerOutorderPre.getState());
        }
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("stock_in_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("stock_in_time", eDate + " 23:59:59");
        }
        queryWrapper.inSql("id","SELECT  a.order_id FROM t_flower_outorder_preinfo a LEFT JOIN flower_storehouse b on   a.storehouse = b.code  LEFT JOIN flower_storehouse_detail c  on b.id = c.mainid  WHERE personid = '" + sysUser.getId() + "'" );
        QueryGenerator.installAuthMplus(queryWrapper,FlowerOutorderPre.class);

        queryWrapper.orderByDesc("order_no");
        queryWrapper.orderByDesc("create_time");
        IPage<FlowerOutorderPre> pageList = flowerOutorderPreService.page(page, queryWrapper);
        return Result.ok(pageList);
    }


    /**
     * 分页列表查询 ------仅用于。销售确认选择预出库单号弹窗使用----去除了 已经被选择过的 与出库单
     *
     * @param flowerOutorderPre
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "预出库单主表-分页列表查询2")
    @ApiOperation(value = "预出库单主表-分页列表查询2", notes = "预出库单主表-------仅用于 销售确认选择预出库单号弹窗使用----去除了 已经被选择过的 与出库单")
    @GetMapping(value = "/list2")
    public Result<?> queryPageList2(FlowerOutorderPre flowerOutorderPre,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        QueryWrapper<FlowerOutorderPre> queryWrapper = new QueryWrapper<>();
        Page<FlowerOutorderPre> page = new Page<FlowerOutorderPre>(pageNo, pageSize);
        if (StringUtils.isNotBlank(flowerOutorderPre.getOrderNo())) {
            queryWrapper.like("order_no", flowerOutorderPre.getOrderNo());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getCreateBy())) {
            queryWrapper.eq("create_user", flowerOutorderPre.getCreateBy());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getStockOutUser())) {
            queryWrapper.eq("stock_out_user", flowerOutorderPre.getStockOutUser());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getChannel())) {
            queryWrapper.eq("channel", flowerOutorderPre.getChannel());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if ( flowerOutorderPre.getState() !=null) {
            queryWrapper.eq("state", flowerOutorderPre.getState());
        }

        queryWrapper.inSql("id","SELECT  a.order_id FROM t_flower_outorder_preinfo a LEFT JOIN flower_storehouse b on   a.storehouse = b.code  LEFT JOIN flower_storehouse_detail c  on b.id = c.mainid  WHERE personid = '" + sysUser.getId() + "'" );
        queryWrapper.notInSql("order_no","select outorder_pre_no from t_flower_pre");

        queryWrapper.orderByDesc("order_no");
        queryWrapper.orderByDesc("create_time");
        IPage<FlowerOutorderPre> pageList = flowerOutorderPreService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "预出库单子表-根据主表id", notes = "预出库单子表-根据主表id")
    @GetMapping(value = "/infolistByOrderNo")
    public Result<?> infolistByOrderNo(@RequestParam("orderNo") String orderNo) {
        List<FlowerOutorderPreinfo> flowerOutorderPreinfos = flowerOutorderPreinfoService.selectByMainNo(orderNo);
        return Result.ok(flowerOutorderPreinfos);
    }

    /**
     * 添加
     *
     * @param flowerOutorderPrePage
     * @return
     */
    @AutoLog(value = "预出库单主表-添加")
    @ApiOperation(value = "预出库单主表-添加", notes = "预出库单主表-添加")
    @PostMapping(value = "/add")
    public synchronized Result<?> add(@RequestBody FlowerOutorderPrePage flowerOutorderPrePage) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorderPre flowerOutorderPre = new FlowerOutorderPre();
        BeanUtils.copyProperties(flowerOutorderPrePage, flowerOutorderPre);
        String channel = flowerOutorderPre.getChannel();
        String accountno = flowerOutorderPre.getAccountno();
        if (StringUtils.isBlank(channel)) {
            throw new RuntimeException("请先选择渠道！");
        }
        /*if (StringUtils.isBlank(accountno)) {
            throw new RuntimeException("请先选择账号！");
        }*/
        //自动生成出库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateNo = simpleDateFormat.format(new Date());
        String refex = "CH-YCK-" + dateNo;
        LambdaQueryWrapper<FlowerOutorderPre> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FlowerOutorderPre::getOrderNo, refex);
        lambdaQueryWrapper.orderByDesc(FlowerOutorderPre::getOrderNo);
        List<FlowerOutorderPre> list = flowerOutorderPreService.list(lambdaQueryWrapper);
        String oldNo = "";
        if (list.size() > 0) {
            oldNo = list.get(0).getOrderNo();
        }
        String no1 = CommonUtil.getNo("CH-YCK-", oldNo, 3);
        flowerOutorderPre.setOrderNo(no1);//自动生成出库单号
        //自动生成出库单号========end====
        flowerOutorderPre.setState(-1);//待确认
        flowerOutorderPreService.saveMain(flowerOutorderPre, flowerOutorderPrePage.getFlowerOutorderPreinfoList());

        return Result.ok("申请成功");
    }


    /**
     * 编辑
     *
     * @param flowerOutorderPrePage
     * @return
     */
    @AutoLog(value = "预出库单主表-编辑")
    @ApiOperation(value = "预出库单主表-编辑", notes = "预出库单主表-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> edit(@RequestBody FlowerOutorderPrePage flowerOutorderPrePage) {
        FlowerOutorderPre flowerOutorderPre = new FlowerOutorderPre();
        BeanUtils.copyProperties(flowerOutorderPrePage, flowerOutorderPre);
        if (flowerOutorderPrePage.getState().compareTo(-1) != 0) {
            return Result.error("已确认出库的数据不可再修改。请先撤销确认");
        }
        FlowerOutorderPre flowerOutorderPreEntity = flowerOutorderPreService.getById(flowerOutorderPre.getId());
        if (flowerOutorderPreEntity == null) {
            return Result.error("未找到对应数据");
        }
        if (flowerOutorderPreEntity.getState().compareTo(0) == 0) {
            return Result.error("已出库的预出库申请不可以修改");
        }
        boolean accountState = settleAccountsService.getAccountState(flowerOutorderPrePage.getPeriod());
        if(!accountState){
            throw new RuntimeException("已结账的单据不可编辑！") ;
        }
        flowerOutorderPreService.updateMain(flowerOutorderPre, flowerOutorderPrePage.getFlowerOutorderPreinfoList());


        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "预出库单主表-通过id删除")
    @ApiOperation(value = "预出库单主表-通过id删除", notes = "预出库单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

//        /**
//         * 1、没预出库台账未出库的才可以进行编辑
//         * 2、删除时先把预出库台账的删除，然后重新生成预出库台账
//         */
//        LambdaQueryWrapper<FlowerOutorderPreinfo> flowerOutorderPreinfoQuery = new LambdaQueryWrapper<>();
//        flowerOutorderPreinfoQuery.eq(FlowerOutorderPreinfo::getOrderId, id);
//        List<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoService.list(flowerOutorderPreinfoQuery);
//        for (FlowerOutorderPreinfo flowerOutorderPreinfo : flowerOutorderPreinfoList) {
//            log.info( "查找预出库申请删除后预出库台账未删除情况====单独删除======预出库申请子表id" +flowerOutorderPreinfo.getId() );
//
//            flowerTagInfoService.BackPreOutTagInfo(flowerOutorderPreinfo.getId());
//        }
//
        //删除主子表
        flowerOutorderPreService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "预出库单主表-批量删除")
    @ApiOperation(value = "预出库单主表-批量删除", notes = "预出库单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        if(StringUtils.isBlank(ids)){
            return Result.error("请选择数据！");
        }
        //删除主子表
        this.flowerOutorderPreService.delBatchMain(Arrays.asList(ids.split(",")));

        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "预出库单主表-通过id查询")
    @ApiOperation(value = "预出库单主表-通过id查询", notes = "预出库单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerOutorderPre flowerOutorderPre = flowerOutorderPreService.getById(id);
        if (flowerOutorderPre == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(flowerOutorderPre);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "预出库单子表通过主表ID查询")
    @ApiOperation(value = "预出库单子表主表ID查询", notes = "预出库单子表-通主表ID查询")
    @GetMapping(value = "/queryFlowerOutorderPreinfoByMainId")
    public Result<?> queryFlowerOutorderPreinfoListByMainId(@RequestParam(name = "id", required = true) String id,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
//        List<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoService.selectByMainId(id);
        Page<FlowerOutorderPreinfo> page = new Page<FlowerOutorderPreinfo>(pageNo, pageSize);
        LambdaQueryWrapper<FlowerOutorderPreinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerOutorderPreinfo::getOrderId, id);
        IPage<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoService.page(page, lambdaQueryWrapper);

        return Result.ok(flowerOutorderPreinfoList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerOutorderPre
     */
    @RequestMapping(value = "/exportXlsAll")
    @PermissionData(pageComponent = "flower/FlowerOutorderPreList")
    @ApiOperation(value = "全部导出-按时间段导出", notes = " -全部导出-按时间段导出")
    public ModelAndView exportXlsAll(HttpServletRequest request, FlowerOutorderPre flowerOutorderPre,
                                     @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                     @RequestParam(value = "eDate", defaultValue = "") String eDate) {
        // Step.1 组装查询条件查询数据
//        QueryWrapper<FlowerOutorderPre> queryWrapper = QueryGenerator.initQueryWrapper(flowerOutorderPre, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        QueryWrapper<FlowerOutorderPre> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(flowerOutorderPre.getOrderNo())) {
            queryWrapper.like("order_no", flowerOutorderPre.getOrderNo());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getCreateBy())) {
            queryWrapper.eq("create_user", flowerOutorderPre.getCreateBy());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getStockOutUser())) {
            queryWrapper.eq("stock_out_user", flowerOutorderPre.getStockOutUser());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getChannel())) {
            queryWrapper.eq("channel", flowerOutorderPre.getChannel());
        }
        if (StringUtils.isNotBlank(flowerOutorderPre.getPhone())) {
            queryWrapper.eq("phone", flowerOutorderPre.getPhone());
        }
        if ( flowerOutorderPre.getState() !=null) {
            queryWrapper.eq("state", flowerOutorderPre.getState());
        }
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("stock_in_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("stock_in_time", eDate + " 23:59:59");
        }


        queryWrapper.orderByAsc("stock_in_time");
        queryWrapper.orderByAsc("create_time");

        queryWrapper.inSql("id","SELECT  a.order_id FROM t_flower_outorder_preinfo a LEFT JOIN flower_storehouse b on   a.storehouse = b.code  LEFT JOIN flower_storehouse_detail c  on b.id = c.mainid  WHERE personid = '" + sysUser.getId() + "'" );
        QueryGenerator.installAuthMplus(queryWrapper,FlowerOutorderPre.class);

        //Step.2 获取导出数据
        List<FlowerOutorderPre> queryList = flowerOutorderPreService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<FlowerOutorderPre> flowerOutorderPreList = new ArrayList<FlowerOutorderPre>();
        if (oConvertUtils.isEmpty(selections)) {
            flowerOutorderPreList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            flowerOutorderPreList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<FlowerOutorderPrePage> pageList = new ArrayList<FlowerOutorderPrePage>();
        for (FlowerOutorderPre main : flowerOutorderPreList) {
            FlowerOutorderPrePage vo = new FlowerOutorderPrePage();
            BeanUtils.copyProperties(main, vo);
            List<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoService.selectByMainId(main.getId());
            vo.setFlowerOutorderPreinfoList(flowerOutorderPreinfoList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "预出库单主表列表");
        mv.addObject(NormalExcelConstants.CLASS, FlowerOutorderPrePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("预出库单主表数据", "导出人:" + sysUser.getRealname(), "预出库单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FlowerOutorderPrePage> list = ExcelImportUtil.importExcel(file.getInputStream(), FlowerOutorderPrePage.class, params);
                for (FlowerOutorderPrePage page : list) {
                    FlowerOutorderPre po = new FlowerOutorderPre();
                    BeanUtils.copyProperties(page, po);
                    flowerOutorderPreService.saveMain(po, page.getFlowerOutorderPreinfoList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 导出excel  出库单
     *
     * @param request
     * @param flowerOutorderPre
     * @return
     */
    @RequestMapping(value = "/exportXlsForOut")
    public ModelAndView exportXlsForOut(HttpServletRequest request, FlowerOutorderPre flowerOutorderPre) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//        TemplateExportParams params = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\muban.xlsx");
        if (StringUtils.isBlank(tempPreExcelOut)) {
            throw new RuntimeException("还未配置导出模板，请联系管理员配置导出模板");
        }
        TemplateExportParams params = new TemplateExportParams(tempPreExcelOut);

        String id = flowerOutorderPre.getId();
        flowerOutorderPre = flowerOutorderPreService.getById(id);

        Map<String, Object> map = new HashMap<String, Object>();

        Date stockInTime = flowerOutorderPre.getStockInTime();
        if (stockInTime == null) {
            stockInTime = new Date();
        }

        String stockOutUser = flowerOutorderPre.getStockOutUser();
        if (StringUtils.isBlank(stockOutUser)) {
            stockOutUser = "";
        }
        String phone = flowerOutorderPre.getPhone();
        if (StringUtils.isBlank(phone)) {
            phone = "";
        }

        String address = flowerOutorderPre.getAddress();
        if (StringUtils.isBlank(address)) {
            address = "";
        }
        String finaSureUser = "";
        if (StringUtils.isBlank(finaSureUser)) {
            finaSureUser = "";
        }
        map.put("orderNo", flowerOutorderPre.getOrderNo());
        map.put("user", flowerOutorderPre.getStockOutUser());
        map.put("stockInTime", simpleDateFormat.format(stockInTime));
        map.put("phone", phone);
        map.put("stockOutUser", stockOutUser);//经办人
        map.put("businessPerson", finaSureUser);//审核人
        map.put("address", address);
        map.put("nowTime", simpleDateFormat.format(new Date()));
        List<FlowerOutorderPreinfo> flowerPreinfoList = flowerOutorderPreinfoService.selectByMainId(flowerOutorderPre.getId());

        if (flowerPreinfoList.size() == 0) {
            throw new RuntimeException("没有出库详情不能生成出库单");
        }
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        BigDecimal countPrice = BigDecimal.ZERO;
        BigDecimal countNum =  BigDecimal.ZERO;
        for (FlowerOutorderPreinfo flowerPreinfo : flowerPreinfoList) {
            Map<String, Object> lm = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(flowerPreinfo.getStorehouse())) {
                QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("code", flowerPreinfo.getStorehouse());
                FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
                lm.put("storehouse", house.getName());
            } else {
                lm.put("storehouse", "");
            }
            lm.put("variety", flowerPreinfo.getVariety());
            lm.put("packingSpecifications", flowerPreinfo.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerPreinfo.getFlowerPoleLength());
            lm.put("number", flowerPreinfo.getNumber());

            countNum =  countNum.add(flowerPreinfo.getNumber() );

            if (StringUtils.isNotBlank(flowerPreinfo.getCost())) {
//                Result<String> dd = sysDictServiceClient.getDictTextOpen("ch_cost",
//                        flowerPreinfo.getCost());
                String costname = sysDictService.queryDictTextByKey("ch_cost", flowerPreinfo.getCost());
                lm.put("cost", costname);
            } else {
                lm.put("cost", "");
            }
            listMap.add(lm);
        }
        if (flowerPreinfoList.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMap.add(lm);
        }
        map.put("countPrice", String.valueOf(countPrice));
        map.put("countNum", String.valueOf(countNum));
        map.put("maplist", listMap);

        ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
        mv2.addObject(TemplateExcelConstants.PARAMS, params);
        mv2.addObject(TemplateExcelConstants.MAP_DATA, map);
        return mv2;
    }

    @AutoLog(value = "基地管理员审核")
    @ApiOperation(value = "基地管理员审核", notes = "基地管理员审核---占用库存")
    @GetMapping(value = "/baseMangeSure")
    public Result<?> baseMangeSure(@RequestParam("id") String id) {
            flowerOutorderPreService.baseMangeSure(id);
        return Result.ok("确认成功！");
    }

    @AutoLog(value = "基地管理员审核-撤销")
    @ApiOperation(value = "基地管理员审核-撤销", notes = "基地管理员审核-撤销")
    @GetMapping(value = "/baseMangeSureBack")
    public Result<?> baseMangeSureBack(@RequestParam("id") String id) {
        FlowerOutorderPre byId = flowerOutorderPreService.getById(id);
        String pipMange = byId.getPipMange();
        String baseMange = byId.getBaseMange();
        Integer state = byId.getState();
        if(state.compareTo(0) != 0){
            throw new RuntimeException("已出库的不可再撤销审核！");
        }
        if (StringUtils.isBlank(baseMange)) {
            throw new RuntimeException("基地管理员还未审核！");
        }
        if (StringUtils.isNotBlank(pipMange)) {
            throw new RuntimeException("运管已经备案过了！");
        }
        byId.setState( -1);
        byId.setBaseMange( "");
        byId.setBaseMangeTime( null);
        flowerOutorderPreService.updateById(byId);
        return Result.ok("撤销成功！");
    }
    @AutoLog(value = "运管备案")
    @ApiOperation(value = "运管备案", notes = "运管备案")
    @GetMapping(value = "/pipMange")
    public Result<?> pipMange(@RequestParam("id") String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorderPre byId = flowerOutorderPreService.getById(id);
        String pipMange = byId.getPipMange();
        String baseMange = byId.getBaseMange();
        Integer state = byId.getState();
        if(state.compareTo(0) != 0){
            throw new RuntimeException("已出库的不可再审核！");
        }
        if (StringUtils.isBlank(baseMange)) {
            throw new RuntimeException("请先进行基地管理员审核！");
        }
        if (StringUtils.isNotBlank(pipMange)) {
            throw new RuntimeException("运管已经备案过了！");
        }

        byId.setBaseMangeTime( byId.getBaseMangeTime());
        byId.setPipMange(sysUser.getRealname());
        byId.setPipMangeTime(new Date());
        flowerOutorderPreService.updateById(byId);
        return Result.ok("确认成功！");
    }

    @AutoLog(value = "运管备案-撤销")
    @ApiOperation(value = "运管备案-撤销", notes = "运管备案-撤销")
    @GetMapping(value = "/pipMangeBack")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> pipMangeBack(@RequestParam("id") String id) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorderPre byId = flowerOutorderPreService.getById(id);
        String pipMange = byId.getPipMange();
        String baseMange = byId.getBaseMange();
        Integer state = byId.getState();
        if(state.compareTo(0) != 0){
            throw new RuntimeException("已出库的不可再撤销审核！");
        }
        if (StringUtils.isBlank(pipMange)) {
            throw new RuntimeException("还未运管备案！");
        }
        byId.setBaseMangeTime( byId.getBaseMangeTime());
        byId.setPipMange("");
        byId.setPipMangeTime(null);
        flowerOutorderPreService.updateById(byId);
        return Result.ok("撤销成功！");
    }


    /**
     * 预出库单主表-确认预出库
     * @descriptionauthor
     * @author gf
     * 2022-11-10 10:19
     * [flowerOutorderPrePage]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "预出库单主表-库管确认预出库")
    @ApiOperation(value = "预出库单主表-确认预出库", notes = "预出库单主表-库管确认预出库")
    @GetMapping(value = "/sureOut")
    public Result<?> sureOut(@RequestParam("id") String id) {
        Integer rest = 0;
        // 设置redis锁
//        Object isLock = redisUtil.get(CommonUtil.SUBTAGINFOKEY);
//        if(ObjectUtils.isNotEmpty(isLock)){
//            Integer isLock2 = Integer.parseInt(isLock.toString());
//            if(isLock2==1){
//                throw new RuntimeException("其他人员正在出库，请稍等片刻重试！");
//            }
//        }
//        redisUtil.set(CommonUtil.SUBTAGINFOKEY, 1); //锁定
//        redisUtil.expire(CommonUtil.SUBTAGINFOKEY, CommonUtil.SUBTAGINFOTIME );

        synchronized(CommonUtil.SUBTAGINFOKEY) {
            FlowerOutorderPre flowerOutorderPre = flowerOutorderPreService.getById(id);
            //生成预出库台账,修改入库台账状态
            rest = flowerOutorderPreService.saveTagPreBach(flowerOutorderPre);
        }
       //解除锁定
//        redisUtil.del( CommonUtil.SUBTAGINFOKEY );
        return Result.ok("出库成功");
    }
    /**
     * 预出库单主表--撤销确认预出库
     * @descriptionauthor
     * @author gf
     * 2022-11-10 10:19
     * [flowerOutorderPrePage]
     * @return org.jeecg.common.api.vo.Result<?>
     */
    @AutoLog(value = "预出库单主表-撤销确认预出库")
    @ApiOperation(value = "预出库单主表-撤销确认预出库", notes = "预出库单主表-撤销确认预出库")
    @GetMapping(value = "/sureOutBack")
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Result<?> sureOutBack(@RequestParam("id") String id) {
        synchronized(CommonUtil.SUBTAGINFOKEY) {
            FlowerOutorderPre flowerOutorderPre = flowerOutorderPreService.getById(id);
            flowerOutorderPreService.saveTagPreBachBack(flowerOutorderPre);
        }
        return Result.ok("撤销出库成功");
    }

}
